#!/bin/bash
# Creates a .deb package for searx-qt
# run from: searx-qt root (where setup.py is).
PKGNAME=
VERSION=
REL=
ARCH=
MAINTAINER=
DESC=
URL=
MAKEDEPENDS=
DEPENDS=

ROOT=$(pwd)
SRCDIR=$(realpath "src")
PKGDIR=$(realpath "pkg")

if [[ ! -d "${SRCDIR}" ]]; then
  mkdir "${SRCDIR}"
fi


function get_sources() {
  :
}

function prepare() {
  :
}
function build() {
  :
}
function package() {
  :
}


function check_deps() {
  MISSING=()
  for pkg in "${MAKEDEPENDS[@]}"; do
    dpkg -s "${pkg}" > /dev/null 2>&1
    if [[ $? -ne 0 ]]; then
      MISSING+=("${pkg}")
    fi
  done

  for pkg in "${DEPENDS[@]}"; do
    dpkg -s "${pkg}" > /dev/null 2>&1
    if [[ $? -ne 0 ]]; then
      MISSING+=("${pkg}")
    fi
  done

  if [[ ${#MISSING[@]} -ne 0 ]]; then
    echo "The following packages are missing, please install them first:"
    echo ""
    echo "  ${MISSING[@]}"
    echo ""
    exit 1
  fi
}


function exec() {
  # Check dependencies
  check_deps

  # Make sure the pkg dir is fresh
  if [[ -d "${PKGDIR}" ]]; then
    rm -rf "${PKGDIR}"
  fi
  mkdir "${PKGDIR}"

  # Get the sources
  get_sources
  if [[ $? -ne 0 ]]; then
    exit 1
  fi

  # Prepare
  prepare
  if [[ $? -ne 0 ]]; then
    exit 1
  fi

  # Build the sources
  build
  if [[ $? -ne 0 ]]; then
    exit 1
  fi

  # Package
  package
  if [[ $? -ne 0 ]]; then
    exit 1
  fi

  mkdir "${PKGDIR}/DEBIAN"
  echo "Package: ${PKGNAME}
Version: ${VERSION}
Maintainer: ${MAINTAINER}
Depends: ${DEPENDS}
Architecture: ${ARCH}
Homepage: ${URL}
Description: ${DESC}" \
  > "${PKGDIR}/DEBIAN/control"

  dpkg --build "${PKGDIR}"
  if [[ $? -ne 0 ]]; then
    exit 1
  fi

  cd "${ROOT}"
  mv pkg.deb "${PKGNAME}-${VERSION}-${REL}_${ARCH}.deb"
}
